import { ref } from "vue";
import { getExceptionList } from "@/api/exceptionDetail";
import { groupBy, forEach } from 'lodash'

export default function useRelationTab({props,detailInfo:detailData}) {

  const relateLoading = ref(false)
  const relateList = ref([])
  // 构造关联分析的table数据
  const buildRelateList = (data) => {
    let relateList = [];
    const groupData = groupBy(data, 'dstWorkloadName');
    forEach(groupData, (list, name) => {
      relateList.push({
        id: name,
        src: list[0].srcWorkloadName,
        dst: name,
        exceptionCount: list.length || 0,
        list,
      })
    })
    return relateList;
  }
  // 获取关联分析列表数据
  const getRelateList = () => {
    relateLoading.value = true
    const detailInfo = detailData.value
    const listParams = props.listParams
    const maxSize = props.maxSize
    const params = {
      startPage: 1,
      size: maxSize,
      // 关联分析的开始和结束时间是为当前请求的开始时间和结束时间，结束时间:requestTime+requestTotalTime
      startTime: "",
      startTimeStamp: detailInfo?.requestTimeStamp,
      endTime: "",
      endTimeStamp:
        Number(detailInfo?.requestTimeStamp) +
        Number(detailInfo?.requestTotalTime) / 1000000,
      masterIps: listParams.masterIps,
      srcWorkloadList: [
        {
          masterIp: detailInfo?.dstMasterip?.key || "",
          namespace: detailInfo?.dstNamespace || "",
          workloadKind: detailInfo?.dstWorkloadKind || "",
          workloadName: detailInfo?.dstWorkloadName || "",
        },
      ],
      id: detailInfo?.id,
    };
    getExceptionList(params)
      .then((res) => {
        const data = res.data?.responseEsPageVO?.records || [];
        const list = buildRelateList(data);
        console.log(list, 'list');

        relateList.value = list
      })
      .finally(() => {
        relateLoading.value = false
      });
  };
  return {
    relateLoading,
    relateList,
    getRelateList
  }
}
